package com.heima.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserConstants;
import com.heima.feign.ArticleFeign;
import com.heima.feign.WemediaFeign;
import com.heima.mapper.ApUserMapper;
import com.heima.mapper.ApUserRealnameMapper;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.service.ApUserRealnameService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Log4j2
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>
 implements ApUserRealnameService {


    @Autowired
    private ApUserMapper apUserMapper ;

    @Autowired
    private WemediaFeign wemediaFeign ;

    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public ResponseResult ApUserList(AuthDto authDto) {

        //检查参数
        if(authDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数不能为空");
        }

        //分页检查
        authDto.checkParam();

        //根据状态分页查询
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(authDto.getStatus() != null){
            try {
                lambdaQueryWrapper.eq(ApUserRealname::getStatus,authDto.getStatus());
            } catch (Exception e) {
                log.info("根据入参状态查询数据库失败");
                e.printStackTrace();
            }
        }

        //构建分页查询
        IPage pageParam = new Page(authDto.getPage(),authDto.getSize());
        IPage page =page(pageParam,lambdaQueryWrapper);

        //返回查询结果
        PageResponseResult responseResult = new PageResponseResult(authDto.getPage(),authDto.getSize(),
                (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }


    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        //检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //检查状态
        if(checkStatus(status)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //修改状态
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if(dto.getMsg() != null){
            apUserRealname.setReason(dto.getMsg());
        }

        updateById(apUserRealname);

        //如果审核状态是通过,创建自媒体账户,创建作者信息
        if(status.equals(UserConstants.PASS_AUTH)){
            //创建自媒体账户,创建作者信息
            ResponseResult result =createWmUserAndAuthor(dto);
            if (result != null){
                return result ;
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体用户 ,创建作者信息
     * @param dto
     * @return
     */
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //拿到用户认证信息
        ApUserRealname userRealname = getById(dto.getId());
        //根据用户认证信息user_id拿到用户信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        //判断用户信息是否存在,不存在,拒绝创建自媒体账号和作者账号;存在:创建
        if(apUser == null){
            //创建自媒体用户失败
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //创建自媒体账号
        //使用feign远程接口,查询自媒体账号是否存在
        WmUser wmUser = wemediaFeign.wemediafind(apUser.getName());

        //如果自媒体账户不存在的话,创建,在创建作者账号,如果自媒体账号存在,直接创建作者账号
        if(wmUser == null){
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wemediaFeign.wemediaSave(wmUser);
        }


        //创建作者
        createAuther(wmUser);
        apUser.setFlag((short)1);
        apUserMapper.updateById(apUser);
        return null ;
    }


    /**
     * 创建作者
     * @param wmUser
     */
    private void createAuther(WmUser wmUser) {
        Integer apUserId = wmUser.getApUserId();
        ApAuthor apAuthor = articleFeign.findById(apUserId);
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setUserId(apUserId);
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(UserConstants.AUTH_TYPE);
            articleFeign.saveApAuther(apAuthor);
        }
    }

    /**
     * 检查状态
     * @param status
     * @return
     */
    private boolean checkStatus(Short status){
       if(status == null ||(!status.equals(UserConstants.FAIL_AUTH) && !status.equals(UserConstants.PASS_AUTH))){
            return true ;
       }
         return false ;
    }
}
